const router = require('koa-router')();

router.prefix('/api')


router.post('/registry', async ctx => {
    const { phone, password } = ctx.request.body;
    const res = await ctx.searchQuery(`select phone from user WHERE phone='${phone}'`);
    if(res.length){
        ctx.body = {
           code: "FAIL",
           msg:"该用户译注测",
           status: 200
        }
        return;
    }
    const addres = await ctx.searchQuery(`INSERT INTO user ( phone, password )
    VALUES
    ('${phone}', '${password}' );`);
    ctx.body = {
        code: "SUCCESS",
        msg:"注册成功",
        status: 200
    }
})

router.post('/login', async ctx => {
    const { phone, password } = ctx.request.body;
    const res = await ctx.searchQuery(`select * from user WHERE phone='${phone}' AND password='${password}';`);
    if(res.length){
        ctx.body = {
            code: "SUCCESS",
            msg:"登录成功",
            status: 200
        }
        return;
    }
    ctx.status = 417;
    ctx.body = {
        code: "FAIL",
        msg:"用户名密码输入有误",
        status: 417
    }
})

router.post("/addCourse", async ctx => {
    const {name, jineng, lilun, date} = ctx.request.body;
    const addres = await ctx.searchQuery(`INSERT INTO courseList ( name, jineng, lilun, date )
    VALUES
    ('${name}', '${jineng}', '${lilun}', '${date}');`);
    if(addres.insertId){
        ctx.body = {
            code: "SUCCESS",
            msg:'数据添加成功',
            status: 200,
            data:{
                id:addres.insertId
            }
        }
    } 
})

router.get("/searchCourse", async ctx => {
    const {id,pageNum,pageSize} = ctx.query;

    if(id){
        const res = await ctx.searchQuery(`select * from courseList WHERE id=${id*1};`);
       if(res.length){
            ctx.body = {
                code: "SUCCESS",
                msg:'数据查询成功',
                status: 200,
                data:res
            }
       } else {
            ctx.body = {
                code: "SUCCESS",
                msg:'没有该数据',
                status: 200,
                data:null
            }
       }
       return;
    }
    const sumszie = await ctx.searchQuery(`SELECT * FROM courseList`);
    const listRes = await ctx.searchQuery(`SELECT *
    FROM courseList
    LIMIT ${pageSize * 1} OFFSET ${(pageNum - 1) * pageSize}`)
    ctx.body = {
        code: "SUCCESS",
        msg:'数据CHAXUN成功',
        status: 200,
        data: {
            listRes,
            pageSize: sumszie.length
        }
    }
})

module.exports = router;